#!/usr/bin/python3
# coding: utf-8
# file: queue_.py
# 2018-06-15
import queue

def print_doc(func, *args):
	def wapper(*args):
		d = func(*args)
		print(func.__doc__, d)
	return wapper

q = queue.Queue(2)

q.put('a')

@print_doc
def q_empty():
	'检查队列是否为空'
	return q.empty()

@print_doc
def q_full():
	'检查队列是否已满'
	return q.full()

@print_doc
def q_get():
	'从队列取一个元素'
	rs = q.get()
	print('get', rs)
	return rs

@print_doc
def q_task_done(q):
	'队列取完后退出, task_done 发送信号'
	while True:
		rs = q.get()
		print('get', rs)
		q.task_done()

import threading

def url_task_done(url_q, proxy_q, rs_q):
	while True:
		try:
			r = url_q.get()
			print('put', r)
			rs_q.put(r)
		except:
			pass
		url_q.task_done()


def append_rs(rs_q, rs):
	while True:
		try:
			r = rs_q.get()
			print('get', r)
			if r:
				rs.append(r)
		except:
			pass
		rs_q.task_done()


def use_thread_with_queue():
	url_q = queue.Queue()
	proxy_q = queue.Queue()
	rs_q = queue.Queue()
	rs = []

	for _ in range(2):
		t = threading.Thread(target=url_task_done, args=(url_q, proxy_q, rs_q))
		t.setDaemon(True)
		t.start()

	for i in range(100):
		url_q.put(i)

	for _ in range(8):
		t = threading.Thread(target=append_rs, args=(rs_q, rs))
		t.setDaemon(True)
		t.start()

	url_q.join()
	rs_q.join()
	print(rs)


if __name__ == '__main__':
	q_full()
	q_empty()
	q_get()
	use_thread_with_queue()
